var express = require('express');
const app = require('../app');
var router = express.Router();
const posts = require('../db/Posts');

/* GET home page. */
router.get('/', function (req, res) {
  console.log('PASO')
  posts.fetchAll(`
    SELECT p.id, p.title, p.tags, p.status, t.count AS translations_count 
    FROM posts p 
    INNER JOIN translations t ON t.id = p.translation_id 
    WHERE language = $language ORDER BY p.id ASC
    `,
    {
      $language: process.env.DEFAULT_LANGUAGE
    },
    function (err, rows) {
      console.log('PASO')
      if (err) {
        res.render('partial/error.njk', { error: err })
      } else {
        const columns = ['id', 'title', 'html', 'tags', 'status']
        if (Number(req.cookies.currentId)) {
          posts.fetchByPK(columns, req.cookies.currentId, function (err, row) {
            if (err) {
              res.render('partial/error.njk', { error: err })
            } else {
              res.render('index.njk', { rows: rows, selected: row });
            }
          }
          )
        } else {
          console.log('ELSE');
          posts.fectchFirst(columns, function (err, row) {
            if (err) {
              res.render('partial/error.njk', { error: err })
            } else {
              res.render('index.njk', { rows: rows, selected: row });
            }
          }
          )
        }
      }
      /* posts.fetchOne(`SELECT id, title, html, tags, status FROM posts WHERE ${condition} ORDER BY id ASC LIMIT 1`, param, 
         function (err, row) {
           res.render('index.njk', { rows: rows, selected: row });
         }   
       );*/

    })
});

module.exports = router;
